<!DOCTYPE html><html lang="zh-Hans"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="typescript初学习"><meta name="keywords" content="typescript"><meta name="author" content="晟松"><meta name="copyright" content="晟松"><title>typescript初学习 | 晟松</title><link rel="shortcut icon" href="/logo.png"><link rel="stylesheet" href="/css/index.css?version=1.9.0"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.9.0"><meta name="format-detection" content="telephone=no"><meta http-equiv="x-dns-prefetch-control" content="on"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="dns-prefetch" href="https://hm.baidu.com"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?c34d81d53341febe06a155941e2df16d";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();</script><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容:${query}"}},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  hexoVersion: '5.4.0'
} </script><meta name="generator" content="Hexo 5.4.0"></head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar" data-display="true"><div class="toggle-sidebar-info text-center"><span data-toggle="切换文章详情">切换站点概览</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">目录</div><div class="sidebar-toc__progress"><span class="progress-notice">你已经读了</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-%E5%9F%BA%E7%A1%80%E7%B1%BB%E5%9E%8B"><span class="toc-number">1.</span> <span class="toc-text">1.基础类型</span></a></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="/img/avatar.png"></div><div class="author-info__name text-center">晟松</div><div class="author-info__description text-center">晟松的博客</div><div class="follow-button"><a target="_blank" rel="noopener" href="https://gitee.com/cheng_song">Gitee</a></div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">文章</span><span class="pull-right">52</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">标签</span><span class="pull-right">45</span></a></div></div></div><div id="content-outer"><div id="top-container" style="background-image: url(/img/blog-bg.jpg)"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">晟松</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus">   <a class="site-page" href="/">Home</a><a class="site-page" href="/archives">Archives</a><a class="site-page" href="/tags">Tags</a><a class="site-page" href="/categories">Categories</a></span><span class="pull-right"><a class="site-page social-icon search"><i class="fa fa-search"></i><span> 搜索</span></a></span></div><div id="post-info"><div id="post-title">typescript初学习</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2020-07-29</time><div class="post-meta-wordcount"><span>字数总计: </span><span class="word-count">1.3k</span><span class="post-meta__separator">|</span><span>阅读时长: 5 分钟</span></div></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><p>typescript学习,下面简称ts.有些语法类似于java</p>
<p>typescript是js的一个超集，添加了一些新的扩展.主要目的是为了开发大型应用。</p>
<ul>
<li>类型批注和编译时类型检查</li>
<li>类型推断</li>
<li>类型擦除</li>
<li>接口</li>
<li>枚举</li>
<li>Mixin</li>
<li>泛型编程</li>
<li>名字空间</li>
<li>元组</li>
<li>Await</li>
</ul>
<p>2.使用<strong>npm install -g typescript</strong>安装进行使用，<strong>tsc</strong>是使用的标识，**.ts**是typescript文件扩展名。执行以下命令将 TypeScript 转换为 JavaScript 代码：</p>
<figure class="highlight powershell"><table><tr><td class="code"><pre><span class="line">tsc test.ts</span><br></pre></td></tr></table></figure>

<p>3.TypeScript 程序由以下几个部分组成：</p>
<ul>
<li>模块</li>
<li>函数</li>
<li>变量</li>
<li>语句和表达式</li>
<li>注释</li>
</ul>
<p>每一行指令都是一段语句，可使用分号进行语句隔开，使合理。</p>
<p>4.TypeScript 面向对象编程实例：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Site</span> </span>&#123; </span><br><span class="line">   name():<span class="keyword">void</span> &#123; </span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">&quot;Runoob&quot;</span>) </span><br><span class="line">   &#125; </span><br><span class="line">&#125; </span><br><span class="line"><span class="keyword">var</span> obj = <span class="keyword">new</span> Site(); </span><br><span class="line">obj.name();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 函数定义</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">greet</span>(<span class="params"></span>):<span class="title">string</span> </span>&#123; <span class="comment">// 返回一个字符串，需要写明返回类型</span></span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;Hello World&quot;</span> </span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>

<p>编译后生成的 JavaScript 代码如下：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> Site = <span class="comment">/** <span class="doctag">@class </span>*/</span> (<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">Site</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line">    Site.prototype.name = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&quot;Runoob&quot;</span>);</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="keyword">return</span> Site;</span><br><span class="line">&#125;());</span><br><span class="line"><span class="keyword">var</span> obj = <span class="keyword">new</span> Site();</span><br><span class="line">obj.name();</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">greet</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;Hello World&quot;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<hr>
<h5 id="1-基础类型"><a href="#1-基础类型" class="headerlink" title="1.基础类型"></a>1.基础类型</h5><p>any,number,string,boolean,</p>
<p>数组（let arr: number[] = [1, 2];），</p>
<p>元组（let x: [string, number];），</p>
<p>枚举（enum Color {Red, Green, Blue};）</p>
<p>void，null，undefined，never</p>
<p><strong>类型断言</strong>：用来手动指定一个值的类型，即允许变量从一种类型更改为另一种类型。</p>
<p>语法格式：</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">//&lt;类型&gt;值 或 值 as 类型</span></span><br><span class="line"><span class="keyword">var</span> str = <span class="string">&#x27;1&#x27;</span> </span><br><span class="line"><span class="keyword">var</span> str2:number = &lt;number&gt; &lt;any&gt; str   <span class="comment">//str、str2 是 string 类型</span></span><br><span class="line"><span class="built_in">console</span>.log(str2)</span><br></pre></td></tr></table></figure>



<p>ts有些特殊的变量类型，如<strong>any</strong>，一般用于用户的输入，不确定会输入什么。下面定义了存储各种类型的数组。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> arrayList: any[] = [<span class="number">1</span>, <span class="literal">false</span>, <span class="string">&#x27;fine&#x27;</span>];<span class="comment">//ts的变量声明格式</span></span><br><span class="line"><span class="keyword">let</span> myts: number = <span class="number">10</span>;</span><br><span class="line"><span class="keyword">var</span> uname:string = <span class="string">&quot;Runoob&quot;</span>; </span><br><span class="line">arrayList[<span class="number">1</span>] = <span class="number">100</span>;</span><br></pre></td></tr></table></figure>

<p>ts里定义函数的参数可设置<strong>可选</strong>(通过?)，在参数后面需要指明参数类型。还有默认参数</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">buildName</span>(<span class="params">firstName: string = <span class="string">&#x27;abc&#x27;</span>, lastName?: string</span>) </span>&#123;<span class="comment">//可设置默认值</span></span><br><span class="line">    <span class="keyword">if</span> (lastName)</span><br><span class="line">        <span class="keyword">return</span> firstName + <span class="string">&quot; &quot;</span> + lastName;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">        <span class="keyword">return</span> firstName;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">let</span> result1 = buildName(<span class="string">&quot;Bob&quot;</span>);  <span class="comment">// 正确</span></span><br><span class="line"><span class="keyword">let</span> result2 = buildName(<span class="string">&quot;Bob&quot;</span>, <span class="string">&quot;Adams&quot;</span>, <span class="string">&quot;Sr.&quot;</span>);  <span class="comment">// 错误，</span></span><br><span class="line"><span class="keyword">let</span> result3 = buildName(<span class="string">&quot;Bob&quot;</span>, <span class="string">&quot;Adams&quot;</span>);  <span class="comment">// 正确</span></span><br></pre></td></tr></table></figure>

<p>ts的剩余参数，指我们不知道需要传入多少参数。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">addNumbers</span>(<span class="params">...nums:number[]</span>) </span>&#123;<span class="comment">//一般是数组</span></span><br><span class="line">    <span class="keyword">var</span> i;   </span><br><span class="line">    <span class="keyword">var</span> sum:number = <span class="number">0</span>; <span class="comment">//ts的变量声明格式</span></span><br><span class="line">    </span><br><span class="line">    <span class="keyword">for</span>(i = <span class="number">0</span>;i&lt;nums.length;i++) &#123; </span><br><span class="line">       sum = sum + nums[i]; </span><br><span class="line">    &#125; </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;和为：&quot;</span>,sum) </span><br><span class="line"> &#125; </span><br><span class="line"> addNumbers(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>) </span><br></pre></td></tr></table></figure>

<p>ts也可使用函数重载(函数名相同，参数不同)</p>
<p>ts数组可解构(将数组元素赋值给变量)</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> a =[<span class="number">10</span>,<span class="string">&quot;Runoob&quot;</span>] </span><br><span class="line"><span class="keyword">var</span> [b,c] = a <span class="comment">//解构，es6好像有新的解构方式(...)</span></span><br></pre></td></tr></table></figure>

<p>有一些常用数组方法</p>
<ul>
<li>contact(),链接两个数组元素</li>
<li>forEach(),对每个元素进行一次回调函数</li>
<li>pop(),删除最后一个元素</li>
<li>push(),在末尾添加一个元素</li>
<li>slice(),选取数组的一部分</li>
</ul>
<p>ts元组，就是一个数组，但里面的元素类型不同。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> mytuple = [<span class="number">10</span>,<span class="string">&quot;Runoob&quot;</span>]; <span class="comment">// 创建元组</span></span><br></pre></td></tr></table></figure>

<p>ts联合类型，就是一个变量可以有多个类型，以（|）分开。还可形成联合类型数组</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> val:string|number </span><br><span class="line">val = <span class="number">12</span> </span><br><span class="line">val = <span class="string">&quot;Runoob&quot;</span> </span><br></pre></td></tr></table></figure>

<p>ts接口，还是interface定义一个抽象接口，当做一个类型进行使用。也可使用extend继承多个接口进行扩展</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">interface IPerson &#123; </span><br><span class="line">    <span class="attr">firstName</span>:string, </span><br><span class="line">    <span class="attr">lastName</span>:string, </span><br><span class="line">    <span class="attr">sayHi</span>: <span class="function">()=&gt;</span>string </span><br><span class="line">&#125; </span><br><span class="line"> </span><br><span class="line"><span class="keyword">var</span> customer:IPerson = &#123; </span><br><span class="line">    <span class="attr">firstName</span>:<span class="string">&quot;Tom&quot;</span>,</span><br><span class="line">    <span class="attr">lastName</span>:<span class="string">&quot;Hanks&quot;</span>, </span><br><span class="line">    <span class="attr">sayHi</span>: ():<span class="function"><span class="params">string</span> =&gt;</span>&#123;<span class="keyword">return</span> <span class="string">&quot;Hi there&quot;</span>&#125; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>ts类，面向对象编程,也可extend继承,不能继承父类的私有成员(方法和属性)和构造函数，不支持多继承，支持多重继承，可进行重写，和super调用父类属性和方法类可使用接口，使用关键字 implements，并将接口的属性作为类的属性使用。</p>
<figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">car</span></span>&#123; </span><br><span class="line"><span class="comment">// 类作用域,可包含以下几个模块</span></span><br><span class="line"><span class="comment">//字段 - 是类里面声明的变量。字段表示对象的有关数据。</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//构造函数 − 类实例化时调用，可以为类的对象分配内存。</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//方法 − 方法为对象要执行的操作。</span></span><br><span class="line">    <span class="attr">engine</span>:<span class="built_in">string</span>; </span><br><span class="line">    <span class="comment">// 构造函数 </span></span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">engine:<span class="built_in">string</span></span>)</span> &#123; </span><br><span class="line">        <span class="built_in">this</span>.engine = engine </span><br><span class="line">    &#125;  </span><br><span class="line">    <span class="comment">// 方法 </span></span><br><span class="line">    disp():<span class="built_in">void</span> &#123; </span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&quot;发动机为 :   &quot;</span>+<span class="built_in">this</span>.engine) </span><br><span class="line">    &#125; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> car = <span class="comment">/** <span class="doctag">@class </span>*/</span> (<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;<span class="comment">//js代码</span></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">Car</span>(<span class="params">engine</span>) </span>&#123;</span><br><span class="line">        <span class="built_in">this</span>.engine = engine;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 方法 </span></span><br><span class="line">    Car.prototype.disp = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&quot;发动机为 :   &quot;</span> + <span class="built_in">this</span>.engine);</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="keyword">return</span> Car;</span><br><span class="line">&#125;());</span><br></pre></td></tr></table></figure>

<p>ts命名空间，为了解决重名问题。命名空间定义了标识符的可见范围，一个标识符可在多个名字空间中定义，它在不同名字空间中的含义是互不相干的，命名空间可嵌套。使用 <strong>namespace</strong> 来定义，</p>
<figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">namespace</span> SomeNameSpaceName &#123; </span><br><span class="line">   <span class="keyword">export</span> <span class="keyword">interface</span> ISomeInterfaceName &#123;    &#125;  </span><br><span class="line">   <span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">SomeClassName</span> </span>&#123;    &#125; <span class="comment">//export导出表示可外部调用 </span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>5.ts模块</p>
<p>模块是在其自身的作用域里执行，在外部不可见，除非使用 export进行导出，在其他需要使用的地方通过import进行导入。模块使用模块加载器去导入其它的模块，如服务于 Web 应用的 Require.js</p>
<figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">interface</span> SomeInterface &#123; </span><br><span class="line">   <span class="comment">// 代码部分</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> someInterfaceRef = <span class="built_in">require</span>(<span class="string">&quot;./SomeInterface&quot;</span>);</span><br></pre></td></tr></table></figure>

</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">晟松</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://chengsong.info/2020/07/29/typescript初学习/">https://chengsong.info/2020/07/29/typescript初学习/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://chengsong.info">晟松</a>！</span></div></div><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/typescript/">typescript</a></div><nav id="pagination"><div class="prev-post pull-left"><a href="/2020/08/04/node-js%E5%88%9D%E5%AD%A6%E4%B9%A0/"><i class="fa fa-chevron-left">  </i><span>node.js初学习</span></a></div><div class="next-post pull-right"><a href="/2020/07/24/ES6%E5%AD%A6%E4%B9%A0/"><span>ES6初学习</span><i class="fa fa-chevron-right"></i></a></div></nav></div></div><footer class="footer-bg" style="background-image: url(/img/blog-bg.jpg)"><div class="layout" id="footer"><div class="copyright">&copy;2020 - 2023 By 晟松</div><div class="framework-info"><span>驱动 - </span><a target="_blank" rel="noopener" href="http://hexo.io"><span>Hexo</span></a><span class="footer-separator">|</span><span>主题 - </span><a target="_blank" rel="noopener" href="https://github.com/Molunerfinn/hexo-theme-melody"><span>Melody</span></a></div><div class="icp"><a target="_blank" rel="noopener" href="http://www.beian.miit.gov.cn/"><span>湘ICP备2020021729号</span></a></div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv"><i class="fa fa-file"></i><span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.9.0"></script><script src="/js/fancybox.js?version=1.9.0"></script><script src="/js/sidebar.js?version=1.9.0"></script><script src="/js/copy.js?version=1.9.0"></script><script src="/js/fireworks.js?version=1.9.0"></script><script src="/js/transition.js?version=1.9.0"></script><script src="/js/scroll.js?version=1.9.0"></script><script src="/js/head.js?version=1.9.0"></script><script src="/js/search/local-search.js"></script><script>if(/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
  $('#top-container').addClass('is-mobile')
}</script><div class="search-dialog" id="local-search"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章"></div></div></div><hr><div id="local-search-results"><div id="local-hits"></div><div id="local-stats"><div class="local-search-stats__hr" id="hr"><span>由</span> <a target="_blank" rel="noopener" href="https://github.com/wzpan/hexo-generator-search" style="color:#49B1F5;">hexo-generator-search</a>
 <span>提供支持</span></div></div></div><span class="search-close-button"><i class="fa fa-times"></i></span></div><div class="search-mask"></div></body></html>